//
//  YMWebViewController.h
//  对WKWebView的简单封装

#import "YMWebViewController.h"
#import <Masonry/Masonry.h>
@interface YMWebViewController ()<WKNavigationDelegate>
@property (nonatomic, strong) id url;
@property (nonatomic, strong) NSString *requestUrlStr;
@property (nonatomic, strong) NSString *htmlContent;

@property(strong, nonatomic) UIProgressView *progressView;
@end

@implementation YMWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self beginRequest];
}

- (void)dealloc {
    [self.webView stopLoading];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

/**
 初始化view
 */
- (void)initView {
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    [self.view bringSubviewToFront:self.progressView];
}

- (void)viewLayout {
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(1);
    }];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}
-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 开始请求
 */
- (void)beginRequest {
    if (!self.url) {
        [self loadURL:self.url];
    }
}

- (instancetype)initWithURL:(id)URL {
    if (self = [super init]) {
        self.url = URL;
    }
    return self;
}


/**
 加载请求的url
 */
- (void)loadURL:(id)url {
    if ([url isKindOfClass:[NSString class]]) {
        self.requestUrlStr = [NSString  stringWithFormat:@"%@",url];
        _requestUrl = [NSURL URLWithString:self.requestUrlStr];
    }else if ([url isKindOfClass:[NSURL class]]) {
        _requestUrl = (NSURL *)url;
        self.requestUrlStr = _requestUrl.absoluteString;
    }
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:_requestUrl]];
    
}

/*
 加载html内容
 */
- (void)loadHtml:(NSString *)htmlContent {
    if (htmlContent.length  == 0) {
        return;
    }
    
    self.htmlContent = htmlContent;
    [self.webView loadHTMLString:htmlContent baseURL:nil];
}

#pragma mark Private Method
- (void)updateNavigationItems {
    [self.navigationItem setLeftBarButtonItems:nil animated:NO];
    if (self.webView.canGoBack) {

    } else {
    }
}

- (void)updateTitleOfWebVC {
    NSString *title = self.title; //如果title不为空，固定title显示
    title = title.length>0 ? title: [self.webView title]; //否则取 webview加载出来的title
    self.navigationItem.title = title;
}

#pragma mark ================KVO========================
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        float progress = [[change objectForKey:NSKeyValueChangeNewKey] floatValue];
        if (progress < 1) {
            [_progressView setProgress:progress animated:YES];
        } else {
            [_progressView setProgress:0 animated:NO];
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        // Update title of vc.
        [self updateTitleOfWebVC];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark Lazy
- (WKWebView *)webView {
    
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.translatesAutoresizingMaskIntoConstraints = NO;
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return _webView;
}


- (UIProgressView *)progressView {
    if (_progressView) return _progressView;
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.progressTintColor = [UIColor colorWithRed:72.0/255 green:142.0/255 blue:255115.0/255 alpha:1];;
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    return _progressView;
}
@end
